package com.example.weixinapireptile.service.impl;

import cn.hutool.core.collection.CollUtil;
import cn.hutool.core.date.DateUtil;
import cn.hutool.core.util.ObjectUtil;
import com.baomidou.mybatisplus.core.conditions.Wrapper;
import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.core.toolkit.Wrappers;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.example.weixinapireptile.api.RedisCache;
import com.example.weixinapireptile.api.WeiXinApi;
import com.example.weixinapireptile.common.exceptions.BizException;
import com.example.weixinapireptile.common.result.Result;
import com.example.weixinapireptile.dingding.DingDingBot;
import com.example.weixinapireptile.mapper.WxArticleMapper;
import com.example.weixinapireptile.model.Article;
import com.example.weixinapireptile.model.BizData;
import com.example.weixinapireptile.model.WxResultBody;
import com.example.weixinapireptile.common.okhttp.MyCookieStore;
import com.example.weixinapireptile.pojo.entity.WxArticle;
import com.example.weixinapireptile.pojo.entity.WxArticleClassify;
import com.example.weixinapireptile.pojo.query.WxArticleQuery;
import com.example.weixinapireptile.pojo.vo.WxArticleVO;
import com.example.weixinapireptile.reptile.SpiderUtil;
import com.example.weixinapireptile.service.IWxArticleClassifyService;
import com.example.weixinapireptile.service.IWxArticleService;
import com.example.weixinapireptile.common.utils.HttpUtils;
import com.example.weixinapireptile.common.utils.ThreadUtil;
import com.taobao.api.ApiException;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.text.SimpleDateFormat;
import java.time.LocalDate;
import java.time.LocalDateTime;
import java.time.ZoneOffset;
import java.util.Date;
import java.util.List;
import java.util.Map;

/**
 * @author xunuo
 * @description: TODO
 * @datetime 2023年 11月 03日 11:28
 */
@Service
@Slf4j
public class WxArticleServiceImpl extends ServiceImpl<WxArticleMapper, WxArticle> implements IWxArticleService {

    @Autowired
    private IWxArticleClassifyService articleClassifyService;

    @Autowired
    private WxArticleMapper wxArticleMapper;
    @Autowired
    RedisCache redisCache;
    @Override
    public void reptileWxArticle() throws ApiException {
        try {
            // ok
            List<WxArticleClassify> classifyList = articleClassifyService.list();
            if (CollUtil.isNotEmpty(classifyList)) {
                for (WxArticleClassify classify : classifyList) {
                    String format = DateUtil.format(DateUtil.offsetDay(new Date(), -1), "yyyy-MM-dd");
                    //校验近两天数据 有就跳过
                    long count = count(Wrappers.<WxArticle>lambdaQuery().eq(WxArticle::getClassifyId,classify.getId()).gt(WxArticle::getPublishDate, format));
                    if (count>0) continue;

                    log.info("单个公众号爬取当前为:{}",classify.getClassifyName());
                    //获取公众号fack_id

                    WxResultBody<List<BizData>> searchBiz = WeiXinApi.searchBiz(classify.getClassifyName());

                    List<BizData> list = searchBiz.getList();
                    if (list.isEmpty()) {
                        throw new BizException("公众号:" + classify.getClassifyName() + "不存在");
                    }
                    //查找公众号文章列表______爬取
                    for (int i = 0; i < 3; i++) {
                        log.info("单个公众号爬取当前为:{},次数:{}",classify.getClassifyName(),i+1);
                        //count设置为5默认条数 循环三次 保证15条  按照正常公众号有三天
                        WxResultBody<List<Article>> findExList = WeiXinApi.findExList2(list.get(0).getFakeid(), String.valueOf(i), "17");
                        List<Article> exList = findExList.getApp_msg_list();
                        for (Article article : exList) {
                            WxArticle selectOne = baseMapper.selectOne(new LambdaQueryWrapper<WxArticle>()
                                    .eq(WxArticle::getTitle, article.getTitle()).eq(WxArticle::getLink, article.getLink()));
                            if (ObjectUtil.isEmpty(selectOne)) {

                                LocalDate localDateTime = LocalDateTime.ofEpochSecond(article.getCreate_time(), 0, ZoneOffset.ofHours(8)).toLocalDate();
                                //不进行解析
                                //String content = SpiderUtil.getContent(article.getLink()).get("text");
                                //String html = SpiderUtil.getContent(article.getLink()).get("html");
                                // 持久化入库
                                WxArticle wxArticle = new WxArticle();
                                wxArticle.setId(article.getAid());
                                wxArticle.setTitle(article.getTitle());
                                wxArticle.setLink(article.getLink());
                                wxArticle.setHtmlContent(null);
                                wxArticle.setCoverImage(article.getCover());
                                wxArticle.setClassifyId(classify.getId());
                                wxArticle.setPublishDate(localDateTime.toString());
                                wxArticle.setContent(null);
                                baseMapper.insert(wxArticle);
                                log.info("单个公众号爬取保存 id :{}",wxArticle.getId());
                            }
                        }
                        // 线程阻塞，防止访问频繁导致封号
                        ThreadUtil.wait(30);
                    }

                }
            }
        } catch (BizException e) {
            DingDingBot.sendBot();
            redisCache.setCacheObject("wxpqrunstatus", 0);
            log.error("公众号数据获取异常：{}", e);
        } catch (Exception e) {
            DingDingBot.sendBot();
            redisCache.setCacheObject("wxpqrunstatus", 0);
            log.error("微信请求异常：{}", e);
        }
    }

    @Override
    public List<WxArticleVO> listPages(WxArticleQuery wxArticleQuery) {
        return wxArticleMapper.listWxArticleVo(wxArticleQuery);
    }

    @Override
    public WxArticleVO getWxArticleById(String id) {
        return wxArticleMapper.getWxArticleById(id);
    }

    @Override
    public Result test() {
        //获取公众号fack_id
        WxResultBody<List<BizData>> searchBiz = WeiXinApi.searchBiz("化工365");

        List<BizData> list = searchBiz.getList();
        if (list.isEmpty()) {
            throw new BizException("公众号:" + "化工365" + "不存在");
        }
        System.out.println(list.get(0).getFakeid());

        WxResultBody<List<Article>> findExList = WeiXinApi.findExList(list.get(0).getFakeid());
        List<Article> exList = findExList.getApp_msg_list();
        if (!findExList.getBase_resp().getErr_msg().equals("ok")) {
            //todo 清除 cookie  token
            return Result.failed("调用频繁,请重新扫码!");
        }
        System.out.println(exList.size());
        return null;
    }
}
